package com.beiben.trialproduce.samplecar.service.impl;

import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.beiben.common.GlobalConstant;
import com.beiben.experiment.repair.domain.Repair;
import com.beiben.experiment.repair.service.IRepairService;
import com.beiben.statistics.vo.AbillityDataVo;
import com.beiben.statistics.vo.LineDataVo;
import com.beiben.system.file.mapper.FileMapper;
import com.beiben.system.file.service.IFileService;
import com.beiben.system.user.domain.BeiBenUser;
import com.beiben.system.user.mapper.BeiBenUserMapper;
import com.beiben.trialproduce.samplecar.domain.SampleCarExcelVo;
import com.beiben.utils.*;
import com.beiben.utils.excel.ExcelStyleAnnotationCellWriteHandler;
import com.beiben.utils.excel.ExcelUtils;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.impl.SysUserServiceImpl;
import org.apache.poi.ss.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.beiben.trialproduce.samplecar.mapper.SampleCarMapper;
import com.beiben.trialproduce.samplecar.domain.SampleCar;
import com.beiben.trialproduce.samplecar.service.ISampleCarService;

/**
 * 样车Service业务层处理
 * 
 * @author 熊国强
 * @date 2020-11-18
 */
@Service
public class SampleCarServiceImpl implements ISampleCarService 
{
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired
    private SampleCarMapper sampleCarMapper;

    @Autowired
    private FileMapper fileMapper;

    @Autowired
    private IFileService fileService;

    @Autowired
    private IRepairService repairService;

    @Autowired
    private BeiBenUserMapper userMapper;
    /**
     * 查询样车
     * 
     * @param carId 样车ID
     * @return 样车
     */
    @Override
    public SampleCar selectSampleCarById(Long carId)
    {
        return sampleCarMapper.selectSampleCarById(carId);
    }

    /**
     * 查询样车列表
     * 
     * @param sampleCar 样车
     * @return 样车
     */
    @Override
    public List<SampleCar> selectSampleCarList(SampleCar sampleCar)
    {
        List<SampleCar> sampleCarList = sampleCarMapper.selectSampleCarList(sampleCar);
        for(SampleCar slc : sampleCarList){
            List<com.beiben.system.file.domain.File> newFile = new ArrayList<>();
            List<com.beiben.system.file.domain.File> files = slc.getFile();
            Map<String,List<com.beiben.system.file.domain.File>> map = files.stream().collect(Collectors.groupingBy(com.beiben.system.file.domain.File::getName));
            for(String key : map.keySet()){
                List<com.beiben.system.file.domain.File> fList = map.get(key);
                fList.sort(Comparator.comparing(com.beiben.system.file.domain.File::getCreateTime).reversed());
                boolean result = false;
                for(com.beiben.system.file.domain.File f: fList){
                    if("左视图".equals(f.getName())||"右视图".equals(f.getName())||"正视图".equals(f.getName())||"后视图".equals(f.getName())){
                        result = true;
                    }
                }
                if(result){
                    newFile.add(fList.get(0));
                }
            }
            slc.setFile(newFile);
        }
        return sampleCarList;
    }

    /**
     * 新增样车
     * 
     * @param sampleCar 样车
     * @return 结果
     */
    @Override
    public int insertSampleCar(SampleCar sampleCar)
    {
        return sampleCarMapper.insertSampleCar(sampleCar);
    }

    /**
     * 修改样车
     * 
     * @param sampleCar 样车
     * @return 结果
     */
    @Override
    public int updateSampleCar(SampleCar sampleCar)
    {
        return sampleCarMapper.updateSampleCar(sampleCar);
    }

    /**
     * 批量删除样车
     * 
     * @param carIds 需要删除的样车ID
     * @return 结果
     */
    @Override
    public int deleteSampleCarByIds(Long[] carIds)
    {
        fileService.deleteFileByTableIds(GlobalConstant.TRIAL_PRODUCE_SAMPLE_CAR,carIds);
        return sampleCarMapper.deleteSampleCarByIds(carIds);
    }

    /**
     * 删除样车信息
     * 
     * @param carId 样车ID
     * @return 结果
     */
    @Override
    public int deleteSampleCarById(Long carId)
    {
        return sampleCarMapper.deleteSampleCarById(carId);
    }

    @Override
    public String importSampleCar(List<SampleCar> list, Boolean isUpdateSupport) {
        if (StringUtils.isNull(list) || list.size() == 0)
        {
            throw new CustomException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (SampleCar sampleCar : list)
        {
            try
            {
                // TODO: 2020/11/25 工号对应用户ID
                BeiBenUser user = userMapper.selectUserByUserName(sampleCar.getUserName());
                if(StringUtils.isNotNull(user)){
                    sampleCar.setUserId(user.getUserId());
                    // 验证是否存在这各样车
                    SampleCar e = sampleCarMapper.selectSampleCarByYsNum(sampleCar.getYsNum());
                    if (StringUtils.isNull(e))
                    {
                        this.insertSampleCar(sampleCar);
                        successNum++;
                        successMsg.append("<br/>" + successNum + "、编号： " + sampleCar.getYsNum() + " 导入成功");
                    }
                    else if (isUpdateSupport)
                    {
                        sampleCar.setCarId(e.getCarId());
                        this.updateSampleCar(sampleCar);
                        successNum++;
                        successMsg.append("<br/>" + successNum + "、编号: " + sampleCar.getYsNum() + " 更新成功");
                    }
                    else
                    {
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、编号: " + sampleCar.getYsNum() + " 已存在");
                    }
                }else{
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、用户工号: " + sampleCar.getUserName() + " 不存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、编号: " + sampleCar.getYsNum() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共: " + failureNum + " 条数据格式不正确，错误如下：");
            throw new CustomException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共: " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 导出样车列表
     *
     * @param sampleCar 样车
     * @return 样车集合
     */
    @Override
    public AjaxResult downLoadSampleCarExcel(SampleCar sampleCar) {
        String fileName =ExcelUtils.encodingFilename("科研样车库存汇总表");
        List<SampleCarExcelVo> list = sampleCarMapper.selectSampleCarExcelList(sampleCar);
        int i =0;
        for(SampleCarExcelVo scv : list ){
            i++;
            scv.setAccountsNum("1");
            scv.setUnNormalSubtotal("1");
            scv.setStockYearSubtotal("1");
            scv.setNormalStock("√");
            //获取所有图片最新上传的照片
            List<com.beiben.system.file.domain.File> newFile = new ArrayList<>();
            List<com.beiben.system.file.domain.File> files = scv.getFileList();
            Map<String,List<com.beiben.system.file.domain.File>> map = files.stream().collect(Collectors.groupingBy(com.beiben.system.file.domain.File::getName));
            for(String key : map.keySet()){
                List<com.beiben.system.file.domain.File> fList = map.get(key);
                fList.sort(Comparator.comparing(com.beiben.system.file.domain.File::getCreateTime).reversed());
                boolean result = false;
                for(com.beiben.system.file.domain.File f: fList){
                    if("左视图".equals(f.getName())||"右视图".equals(f.getName())||"正视图".equals(f.getName())||"后视图".equals(f.getName())){
                        result = true;
                    }
                }
                if(result){
                    newFile.add(fList.get(0));
                }
            }
            scv.setOrderNum(String.valueOf(i));
            scv.setFileList(newFile);
            if(scv.getFileList().size()>0){
                for(com.beiben.system.file.domain.File fe : scv.getFileList()){
                    String url = fe.getUri().replaceAll("profile","");
                    if("正视图".equals(fe.getName())){
                        scv.setFile1(new File(RuoYiConfig.getProfile()+url) );
                    }
                    if("左视图".equals(fe.getName())){
                        scv.setFile2(new File(RuoYiConfig.getProfile()+url) );
                    }
                    if("右视图".equals(fe.getName())){
                        scv.setFile3(new File(RuoYiConfig.getProfile()+url) );
                    }
                    if("后视图".equals(fe.getName())){
                        scv.setFile4(new File(RuoYiConfig.getProfile()+url) );
                    }
                }
            }
            if(null!=scv.getProductionTime()){
                Long poorDay = com.beiben.utils.DateUtil.getDatePoorDay(new Date(),scv.getProductionTime());
                if(poorDay<365){
                    scv.setOneYear("√");
                }else if(poorDay>=365&&poorDay<=2*365){
                    scv.setOneTwoYear("√");
                }else if(poorDay>2*365&&poorDay<=3*365){
                    scv.setTwoThreeYear("√");
                }else if(poorDay>3*365&&poorDay<=5*365){
                    scv.setThreeFiveYear("√");
                }else if(poorDay>5*365){
                    scv.setFiveYear("√");
                }
            }
        }
        // 这里 需要指定写用哪个class去写，然后写到第一个sheet，名字为模板 然后文件流会自动关闭
        EasyExcel.write(ExcelUtils.getAbsoluteFile(fileName), SampleCarExcelVo.class).registerWriteHandler(myHorizontalCellStyleStrategy()).registerWriteHandler(myAnnotHoriCellStyleStrategy()).sheet("样车")
                .doWrite(list);
        return AjaxResult.success(fileName);
    }

    /**
     * 按id获取文件列表
     *
     * @param id
     * @return
     */
    @Override
    public List<com.beiben.system.file.domain.File> selectFiles(Long id) {
        com.beiben.system.file.domain.File file = new com.beiben.system.file.domain.File();
        file.setTableId(id);
        file.setTableName(GlobalConstant.TRIAL_PRODUCE_SAMPLE_CAR);
        return fileMapper.selectFileList(file);
    }

    /**
     * 修改样车状态
     *
     * @param repair 维修详情
     * @return 结果
     */
    @Override
    public int updateSampleCarState(Repair repair) {
        int result = -1;
        if(repair.getEquipmentState().equals("1")){
            repair.setTableName("3");
            result = repairService.insertRepair(repair);
        }else{
            if(repair.getEquipmentState().equals("0")){
                repair.setTableName(GlobalConstant.TRIAL_PRODUCE_SAMPLE_CAR);
                repair.setRelFinishTime(new Date());
                repair.setIsFinish("Y");
                repairService.updateRepairIsFinish(repair);
            }
            result = sampleCarMapper.updateSampleCarState(repair.getRelIds(),repair.getEquipmentState(),repair.getEquipmentUseState());
        }
        return result;
    }

    private HorizontalCellStyleStrategy myAnnotHoriCellStyleStrategy(){
        return  new ExcelStyleAnnotationCellWriteHandler(SampleCar.class,
                new WriteCellStyle(), new WriteCellStyle());
    }


    private HorizontalCellStyleStrategy myHorizontalCellStyleStrategy(){
        //表头样式策略
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        //设置表头居中对齐
        headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        //表头前景设置淡蓝色
        headWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        WriteFont headWriteFont = new WriteFont();
        headWriteFont.setBold(true);
        headWriteFont.setFontName("宋体");
        headWriteFont.setFontHeightInPoints((short)9);
        headWriteCellStyle.setWriteFont(headWriteFont);
        //内容样式策略
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        WriteFont contentWriteFont = new WriteFont();
        //内容字体大小
        contentWriteFont.setFontName("宋体");
        contentWriteFont.setFontHeightInPoints((short)9);
        contentWriteCellStyle.setWriteFont(contentWriteFont);
        //设置自动换行
        contentWriteCellStyle.setWrapped(true);
        //设置垂直居中
        contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        //设置水平居中
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        //设置边框样式
        setBorderStyle(contentWriteCellStyle);
        //内容风格可以定义多个。
        List<WriteCellStyle>   listCntWritCellSty =  new ArrayList<>();
        listCntWritCellSty.add(contentWriteCellStyle);
//        WriteCellStyle contentWriteCellStyle2 = new WriteCellStyle();
//        // 这里需要指定 FillPatternType 为FillPatternType.SOLID_FOREGROUND 不然无法显示背景颜色。
//        // 头默认了 FillPatternType所以可以不指定。
//        contentWriteCellStyle2.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
//        // 背景绿色
//        contentWriteCellStyle2.setFillForegroundColor(IndexedColors.WHITE.getIndex());
//        //设置垂直居中
//        contentWriteCellStyle2.setVerticalAlignment(VerticalAlignment.CENTER);
//        //设置水平居中
//        contentWriteCellStyle2.setHorizontalAlignment(HorizontalAlignment.CENTER);
        //设置边框样式
//        setBorderStyle(contentWriteCellStyle2);
//        listCntWritCellSty.add(contentWriteCellStyle2);
        // 水平单元格风格综合策略(表头 + 内容)
        return  new HorizontalCellStyleStrategy(headWriteCellStyle, listCntWritCellSty);
    }

    private void setBorderStyle(WriteCellStyle contentWriteCellStyle){
        //设置边框样式
        contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);
        // contentWriteCellStyle.setBottomBorderColor(IndexedColors.BLUE.getIndex()); //颜色
        contentWriteCellStyle.setBorderTop(BorderStyle.THIN);
        contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
        contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);
    }
}
